package com.wl.shop.web;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wl.shop.security.SystemAuthorizingRealm.ShiroUser;
import com.wl.shop.utils.CookieUtils;
import com.wl.shop.utils.Global;
import com.wl.shop.utils.StringUtils;
import com.wl.shop.utils.UserUtils;
import com.wl.shop.utils.ValidateCodeServlet;

@Controller
public class LoginController extends BaseController {
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response){
		ShiroUser user = UserUtils.getPrincipal();
		// 如果已经登录，则跳转到管理首页
		if(user != null){
			return "redirect:" + adminPath;
		}
		return "login";
	}
	
	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model){
		ShiroUser user = UserUtils.getPrincipal();
		
		// 如果已经登录，则跳转到管理首页
		if(user != null){
			return "redirect:" + adminPath;
		}
		String exceptionClassName = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        String error = null;
        if(AuthenticationException.class.getName().equals(exceptionClassName)){
        	error = "验证码错误";
        }else if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }
        
        // 验证失败清空验证码
        request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, "");
        
        model.addAttribute("error", error);
		return "login";
	}
	
	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		
		// 如果已登录，再次访问主页，则退出原账号。
		if ("true".equals(Global.getConfig("notAllowRefreshIndex"))){
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)){
				CookieUtils.setCookie(response, "LOGINED", "true");
			}else if (StringUtils.equals(logined, "true")){
				UserUtils.getSubject().logout();
				return "redirect:" + adminPath + "/login";
			}
		}
		
		return "sys/sysIndex";
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}/welcome")
	public String welcome(){
		return "sys/welcome";
	}
}
